package com.satis.compose.get.processor

import com.google.auto.service.AutoService
import com.satis.compose.get.annotation.PageRoute
import com.squareup.kotlinpoet.FileSpec
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
import javax.tools.Diagnostic

@AutoService(javax.annotation.processing.Processor::class)
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes("com.satis.compose.get.annotation.PageRoute")
@SupportedOptions("moduleName")
class Processor: AbstractProcessor() {
    private var mLogger: Messager? = null
    private var mElementUtils: Elements? = null
    private lateinit var mModuleName: String

    override fun init(processingEnv: ProcessingEnvironment) {
        super.init(processingEnv)
        mLogger = processingEnv.messager
        mElementUtils = processingEnv.elementUtils
        mModuleName = processingEnv.options["moduleName"].toString()
        mLogger?.printMessage(Diagnostic.Kind.NOTE, "$mModuleName：：：：----init")
    }


    override fun process(set: MutableSet<out TypeElement>, roundEnvironment: RoundEnvironment): Boolean {
        mLogger?.printMessage(Diagnostic.Kind.NOTE,"get processing ...")
        val elements = roundEnvironment.getElementsAnnotatedWith(
            PageRoute::class.java
        )
        for (element in elements) {
            mLogger?.printMessage(Diagnostic.Kind.NOTE,"模块:$mModuleName，待处理的PageRoute：${element.simpleName}")
        }
        try {
            val fileSpec = FileSpec.builder("com.satis.compose.get", "PageHost\$$mModuleName")
                .addFunction(PageStoreCreator(elements,mElementUtils!!,mModuleName,mLogger).generateFunSpec())
                .build()
            fileSpec.writeTo(processingEnv.filer)
            fileSpec.writeTo(System.out)
        }catch (e:Exception){

        }
        return false
    }
}